package org.gdkm.el;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

/**
 * 日志服务类. </br> 
 * 用于减低的程序的耦合性. </br> 
 * 日期: 2012-10-13
 * <p>
 * 
 * @author Arylo<<b>arylo.open@gmail.com</b>>
 * @version 1.0
 */
public class LogServer {
	private static String ServerPath = "res/log/Server/";
	private static String ClientPath = "res/log/Client/";
	private static File serverFile = null;
	private static File clientFile = null;
	private static PrintWriter pw = null;
	private static int timeYear = Calendar.getInstance().get(Calendar.YEAR);
	private static int timeMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
	private static int timeDate = Calendar.getInstance().get(Calendar.DATE);
	private static int timeHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
	private static int timeMinute = Calendar.getInstance().get(Calendar.MINUTE);
	private static int timeSecond = Calendar.getInstance().get(Calendar.SECOND);
	private static String fileName = timeYear + "_"
			+ (timeMonth < 10 ? "0" : "") + timeMonth + "_"
			+ (timeDate < 10 ? "0" : "") + timeDate + ".txt";
	private static String timeString = (timeHour < 10 ? "0" : "") + timeHour
			+ ":" + (timeMinute < 10 ? "0" : "") + timeMinute + ":"
			+ (timeSecond < 10 ? "0" : "") + timeSecond + " :: ";

	/**
	 * 构建一个LogServer 对象.
	 */
	public LogServer() {
		if (Intent.getServerLogPath() != null) {
			LogServer.ServerPath = Intent.getServerLogPath();
		}
		if (Intent.getClientLogPath() != null) {
			LogServer.ClientPath = Intent.getClientLogPath();
		}
		createDir(LogServer.ServerPath);
		serverFile = new File(ServerPath);
		createDir(LogServer.ClientPath);
		clientFile = new File(ClientPath);
	}

	private void createDir(String path) {
		File _f = new File(path);
		if (_f.exists() == false) {
			_f.mkdirs();
		}
	}

	/**
	 * 写入服务端日志.
	 * 
	 * @param text 日志内容
	 */
	public static synchronized void writeServerLog(String text) {
		writeLog(createPath(serverFile, ServerPath), text);
	}

	/**
	 * 写入客户端日志.
	 * 
	 * @param text 日志内容
	 */
	public static synchronized void writeClientLog(String text) {
		writeLog(createPath(clientFile, ClientPath), text);
	}

	private static File createPath(File file,String path) {
		if (!file.getName().equals(fileName) == true) {
            file = new File(path + fileName);
            if (!file.exists() == true) {
                try {
                	file.createNewFile();
                } catch (IOException e) {
                	e.printStackTrace();
                }
            }
		}
		return file;
	}
	private static void writeLog(File file, String text) {
		try {
			pw = new PrintWriter(new FileWriter(file, true));
			pw.println(timeString + text);
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
